package com.efeichong.project.service.impl;

import com.efeichong.common.PageData;
import com.efeichong.common.exception.CustomException;
import com.efeichong.common.utils.OptionEmptyFunction;
import com.efeichong.jpa.JExample;
import com.efeichong.jpa.UpdateGlobalConfig;
import com.efeichong.project.domain.dao.db.SysRoleDao;
import com.efeichong.project.domain.entity.db.SysRole;
import com.efeichong.project.domain.vo.RoleVoInfo;
import com.efeichong.project.domain.vo.SysRoleVo;
import com.efeichong.project.service.SysRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author
 * @date 2020/11/25
 * @description 角色
 */
@RequiredArgsConstructor
@Service
public class SysRoleServiceImpl implements SysRoleService {

    private final SysRoleDao sysRoleDao;

    /**
     * 通过id查询
     *
     * @param id 主键
     * @return
     */
    @Override
    public RoleVoInfo getInfo(Long id) {
        return sysRoleDao.selectById(id, RoleVoInfo.class).orElseThrow(OptionEmptyFunction.create());
    }

    /**
     * 分页查询
     *
     * @param sysRoleVo
     * @return
     */
    @Override
    public PageData selectByPage(SysRoleVo sysRoleVo) {
        JExample<SysRole> example = new JExample();
        example.initExample(sysRoleVo);
        return sysRoleDao.selectByPage(example, sysRoleVo.getClass());
    }

    @Override
    public List<SysRoleVo> selectByList(SysRoleVo sysRoleVo) {
        JExample<SysRole> example = new JExample();
        example.initExample(sysRoleVo);
        return sysRoleDao.selectAll(example, sysRoleVo.getClass());
    }

    /**
     * 新增
     *
     * @param sysRoleVo
     * @return
     */
    @Transactional
    @Override
    public void insertSysRole(RoleVoInfo sysRoleVo) {
        sysRoleDao.save(sysRoleVo.toPo(SysRole.class));
    }

    /**
     * 修改
     *
     * @param sysRoleVo
     * @return
     */
    @Transactional
    @Override
    public void updateSysRole(RoleVoInfo sysRoleVo) {
        if (sysRoleVo.getId() == null) {
            throw new CustomException("主键为必传参数");
        }
        sysRoleDao.save(sysRoleVo.toPo(SysRole.class), new UpdateGlobalConfig() {
            @Override
            public String[] ignoreUpdateProps() {
                return null;
            }

            @Override
            public String[] canBeNullProps() {
                return new String[]{"sysMenus"};
            }
        });
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Transactional
    @Override
    public void deleteByIds(List<Long> ids) {
        sysRoleDao.deleteAllByIds(ids);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public void deleteById(Long id) {
        sysRoleDao.deleteById(id);
    }
}
